﻿using System.Collections.Generic;

namespace MvcContrib.Shp.UI
{
    public static class DictionaryHelperExtensions
    {
        /// <summary>
        /// Replaces the dictionary attribute with @key with the value of @attribute.
        /// </summary>
        /// <param name="attributes">The attributes.</param>
        /// <param name="attribute">The attribute to replace.</param>
        /// <param name="key">The key.</param>
        public static void ReplaceAttribute(this IDictionary<string, object> attributes, string attribute, string key)
        {
            if (string.IsNullOrWhiteSpace(attribute) || string.IsNullOrWhiteSpace(key)) return;
            attributes[key] = attribute;
        }

        /// <summary>
        /// Merges the attributes.
        /// </summary>
        /// <param name="attributes">The attributes.</param>
        /// <param name="attribute">The attribute.</param>
        /// <param name="key">The key.</param>
        /// <param name="dictionaryTakesPriority">if set to <c>true</c>, the value in the dictionary will prepend the value of @attribute.</param>
        public static void MergeAttributes(this IDictionary<string, object> attributes, string attribute, string key,
                                           bool dictionaryTakesPriority)
        {
            if (string.IsNullOrWhiteSpace(attribute) || string.IsNullOrWhiteSpace(key)) return;

            var dictionaryAttribute = "";

            if (attributes.ContainsKey(key) && attributes[key] != null)
                dictionaryAttribute = attributes[key].ToString();

            var results = (dictionaryTakesPriority)
                              ? PrioritizeAttributes(dictionaryAttribute, attribute)
                              : PrioritizeAttributes(attribute, dictionaryAttribute);

            if (!string.IsNullOrWhiteSpace(results))
                attributes[key] = results;
        }

        /// <summary>
        /// Prioritizes the attributes.
        /// </summary>
        /// <param name="priority">The priority.</param>
        /// <param name="secondary">The secondary.</param>
        /// <returns></returns>
        private static string PrioritizeAttributes(string priority, string secondary)
        {
            return ((priority ?? "") + " " + (secondary ?? "")).Trim();
        }
    }
}